package com.liu.qqRobot.official.service.impl;

import cn.hutool.http.HttpRequest;
import com.liu.mybatisPlus.official.entity.base.OfficialItemTendency;
import com.liu.mybatisPlus.official.service.OfficialItemTendencyService;
import com.liu.qqRobot.official.service.SyncItemTendencyService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class SyncItemTendencyServiceImpl implements SyncItemTendencyService {

    @Resource
    private OfficialItemTendencyService officialItemTendencyService;

    @Override
    public void syncItemTendency() {
        String body = HttpRequest.get("https://warframe.fandom.com/wiki/Riven_Mods/Weapon_Dispos/All?action=render")
                .execute()
                .body();
        Pattern firstPattern = Pattern.compile("(?<=<li><a href=\"https://warframe.fandom.com/wiki/).+(?=</li>)");
        Matcher firstMatcher = firstPattern.matcher(body);
        List<OfficialItemTendency> officialItemTendencyList = new ArrayList<>();
        while (firstMatcher.find()) {
            OfficialItemTendency officialItemTendency = new OfficialItemTendency();
            officialItemTendencyList.add(officialItemTendency);
            String firstGroup = firstMatcher.group();
            Pattern namePattern = Pattern.compile("(?<=\">).+(?=</a>)");
            Matcher nameMatcher = namePattern.matcher(firstGroup);
            String name = null;
            if (nameMatcher.find()) {
                name = nameMatcher.group();
            }
            Pattern valuePattern = Pattern.compile("(?<=</a> \\().+(?=\\))");
            Matcher valueMatcher = valuePattern.matcher(firstGroup);
            BigDecimal value = null;
            if (valueMatcher.find()) {
                value = new BigDecimal(valueMatcher.group());
            }
            officialItemTendency.setName(name);
            officialItemTendency.setTendency(value);
        }
        officialItemTendencyService.truncateTable();
        officialItemTendencyService.saveBatch(officialItemTendencyList, 5000);
    }
}
